<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-5-11
 * Time: 9:12
 */
namespace app\common\model;

use think\Model;
use think\Db;

/**
 *  评论 模型
 * @package app\admin\model
 */
class Comments extends Model
{
    protected $name = 'qt_comments';
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;


    /**
     *  添加评论
    **/
    public function addComment($user_id,$store_id = 0,$order_id = 0,$engineer_id = 0,$content = '',$images = '')
    {

        $add['uv_id']       =  $user_id;
        $add['store_id']    =  $store_id;
        $add['engineer_id'] =  $engineer_id;
        $add['content']     =  $content;
        $add['images']      =  $images;
        $add['create_time'] =  time();

        if($order_id)
        {
            //获取项目ID
            $orderItem = Orderproject::where('order_id',$order_id)->column('id','id');
            if($orderItem)
            {
                $ids = implode(',',$orderItem);
                $add['project_ids']      =  $ids;
            }
        }


        Db::startTrans();
        try{

            //插入
            $this->insert($add);

            if($order_id)
            {
                $orderEdit['status'] = 4;
                Order::where('id',$order_id)->update($orderEdit);
            }


            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }

    }


    /**
     *  评论列表
    **/
    public function getCommentList($store_id = 0,$engineer_id = 0,$project_id = 0,$limit = 10)
    {

        //门店查询
        if(!empty($store_id))
        {
            $where[] = ['c.store_id','eq',$store_id];
        }

        //技师查询
        if(!empty($engineer_id))
        {
            $where[] = ['c.engineer_id','eq',$engineer_id];
        }

        //项目查询
        if(!empty($project_id))
        {
            $where[] = ['','exp',Db::raw("FIND_IN_SET($project_id,project_ids)")];
        }

        $list = $this::alias('c')
            ->leftJoin('qt_user_viper uv','uv.id = c.uv_id')
            ->where($where)
            ->field('c.id,c.uv_id,c.content,c.images,c.create_time,uv.nickname,uv.avatar')
            ->order('create_time desc')
            ->paginate($limit)
            ->each(function($item){
                $item['avatar'] = checkAvatar($item['avatar']);
                $item['images'] = get_album_array_path($item['images']);
                return $item;
            });

        return $list->items();
    }


}
